package com.jzxy.PingFen.utils;
import com.jzxy.PingFen.pojo.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * ClassName:CacheUtil
 * Package:com.jzxy.utils
 * Description:
 *
 * @Author: dlh
 * @Creat:2024/12/8-12:21
 */
@Slf4j
@Component
public class CacheUtil {
    private final StringRedisTemplate stringRedisTemplate;
    public CacheUtil(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }
    //任意java对象序列化为json并存贮在string类型的key中，设置过期时间
    public void set(String key, Object value, Long time, TimeUnit unit) throws Exception {
        stringRedisTemplate.opsForValue().set(key, JsonUtils.toJson(value), time, unit);
    }
    //任意java对象序列化为json并存贮在string类型的key中，不设置过期时间
    public void set(String key, Object value) throws Exception {
        log.info("存入redis值：{}",JsonUtils.toJson(value));
        stringRedisTemplate.opsForValue().set(key, JsonUtils.toJson(value));
    }

    //任用key查询缓存，反序列化为指定类型
    public <T> T get(String key, Class<T> clazz) throws Exception {
        // 从Redis中获取JSON字符串
        String jsonStr = stringRedisTemplate.opsForValue().get(key);
        if (jsonStr == null) {
            // 如果缓存中不存在该key，返回null
            return null;
        }
        // 将JSON字符串反序列化为指定类型的对象
        return JsonUtils.toObject(jsonStr, clazz);
    }

    // 删除指定key的缓存
    public void delete(String key) {
        try {
            stringRedisTemplate.delete(key);
        } catch (Exception e) {
            log.error("Failed to delete cache with key: {}", key, e);
        }
    }

    public void deleteKeysWithPrefix(String prefix) {
        // 获取所有前缀为 "course:studentCourse:2209122207" 的键
        Set<String> keys = stringRedisTemplate.keys(prefix);

        if (keys != null && !keys.isEmpty()) {
            for (String key : keys) {
                System.out.println("Deleting key: " + key);
                stringRedisTemplate.delete(key);
            }
        }
    }

    public Object get(String key) throws Exception {
        // 从Redis中获取JSON字符串
        String jsonStr = stringRedisTemplate.opsForValue().get(key);
        if (jsonStr == null) {
            // 如果缓存中不存在该key，返回null
            return null;
        }
        // 将JSON字符串反序列化为指定类型的对象
        return JsonUtils.toObject(jsonStr, Object.class);
    }
}
